package com.caac.core.web.action.user;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.caac.core.dm.Menu;
import com.caac.core.dm.Role;
import com.caac.core.service.UserManager;
import com.caac.core.web.action.BaseAction;
import com.caac.core.web.form.BaseForm;
import com.caac.core.web.form.PermissionForm;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright AgileCentury 2004</p>
 * <p>Company: AgileCentury</p>
 * @author <a href="mailto:agile@agilecentury.com">AgileCentury</a>
 * @version 1.0
 */

public class SavePermissionAction extends BaseAction {

    protected ActionForward doExecute(ActionMapping mapping, BaseForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response) throws java.
            lang.Exception {
        PermissionForm myForm = (PermissionForm) form;
        List pList = myForm.getActionList();
        List rList = myForm.getRoleList();
        UserManager um = (UserManager)this.getBean("userManager");

        for (int i = 0; i < rList.size(); i++) {
            Role role = (Role) rList.get(i);
            List permKeys = new ArrayList();
            for (int j = 0; j < pList.size(); j++) {
                Menu menu = (Menu) pList.get(j);
                String permValue = (String) myForm.getHMap().get("JS" +
                        String.valueOf(i) + "QX" + String.valueOf(j) +
                        "_" + menu.getMenuCode() + "_" +
                        nullToStr(menu.getMenuParent()));
                if (permValue != null) {
                    permKeys.add(permValue);
                }
            }
            String[] pKeys = new String[permKeys.size()];
            permKeys.toArray(pKeys);
//            if (permKeys.size() > 0) {
                um.saveMenus(role.getId(), pKeys);
//            }
        }
//        this.getConfig().findPermissions(um);

        myForm.getHMap().clear();
        return this.forward(mapping);
    }

    private static String nullToStr(Object obj) {
        return (obj == null) ? "" : obj.toString();
    }
}
